package com.lzx.gateway.filter;

import com.lzx.gateway.utils.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class WebGlobalFilter implements GlobalFilter, Ordered {
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    //执行过滤功能five_cube_gateway_background
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //放行前台接口和后台登录接口
        if (antPathMatcher.match("/api/**", path) || antPathMatcher.match("/user/sysUser/login", path)) {
            return chain.filter(exchange);
        } else {
            //后台非登录接口，必须登录后才能放行
            HttpHeaders headers = request.getHeaders();
            String token = headers.getFirst("token");
            //如果token过期，拦截
            if (!JwtUtils.checkToken(token)) {
                //拦截
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.setRawStatusCode(HttpStatus.UNAUTHORIZED.value());
                //路由跳转
//                response.getHeaders().set(HttpHeaders.LOCATION, "http://localhost:10000/login");
                return response.setComplete();//结束请求
            } else {
                return chain.filter(exchange);
            }
        }
    }

    //影响的是全局过滤器的执行顺序：值越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
